using System;
using Bookvar.ApplicationModel;
using Bookvar.Collaboration;

namespace BookvarWpf.Windows.Collaboration
{
    public class CollaborationChatPresenter : ICollaborationChatPresenter
    {
        private readonly ICollaborationManager collaborationManager;
        private readonly ICollaborationChatView view;

        public CollaborationChatPresenter(ICollaborationChatView view)
        {
            this.view = view;
            collaborationManager = BookvarApplication.Current.ServiceLayer.GetService<ICollaborationManager>();
            collaborationManager.UserSaid += OnUserSaid;
            collaborationManager.CollaborationStopped += OnCollaborationClosed;
        }

        #region ICollaborationChatPresenter Members

        public void SendMessage(string message)
        {
            collaborationManager.Say(message);
            if (collaborationManager.CurrentCollaborationUser != null)
            {
                view.UserSaid(collaborationManager.CurrentCollaborationUser, message);
            }
        }

        #endregion

        private void OnCollaborationClosed(object sender , EventArgs e)
        {
            Close();
        }

        private void OnUserSaid(object sender, CollaborationUserMessageEventArgs e)
        {
            view.UserSaid(e.User, e.Message);
        }

        private void Close()
        {
            collaborationManager.UserSaid -= OnUserSaid;
            collaborationManager.CollaborationStopped -= OnCollaborationClosed;
            view.Close();
        }
    }
}